package com.mt.restaurant.service.staff.impl;

import com.mt.common.core.web.JsonResult;
import com.mt.common.system.entity.User;
import com.mt.common.system.service.RoleService;
import com.mt.common.system.service.UserService;
import com.mt.restaurant.dao.staff.StaffDao;

import com.mt.common.core.exception.BusinessException;
import com.mt.common.core.web.base.PageDTO;
import com.mt.common.core.web.base.PageResultDTO;
import com.mt.common.core.web.base.BaseEntity;
import com.mt.common.core.web.BaseService;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.mt.restaurant.entity.staff.Staff;
import com.mt.restaurant.service.staff.StaffService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Service
@Transactional
public class StaffServiceBean extends BaseService implements StaffService {

    private static Logger logger = LogManager.getLogger();

	@Autowired
	private StaffDao staffDao;

	@Resource
	private RedisTemplate<String, List<Staff>> redisTemplate;

	@Autowired
	StringRedisTemplate stringRedisTemplate;

	/**
	 * 根据分页参数查询员工集合
	 *
	 * @param pageDTO 分页条件
	 */
	@Override
	public PageResultDTO findStaffs(PageDTO pageDTO){
        pageDTO.setStartIndex((pageDTO.getCurrentPage()-1)*pageDTO.getPageSize());
		//TODO:请在此校验参数的合法性
		this.validateFindStaffs(pageDTO);
		List<Staff> staffDTOS = this.staffDao.findStaffs(pageDTO);
		Long totalCount = this.staffDao.findStaffTotalCount(pageDTO);

		PageResultDTO pageResultDTO = new PageResultDTO();
		pageResultDTO.setTotalCount(totalCount);
		pageResultDTO.setDatas(staffDTOS);

		return pageResultDTO;
	}

	/**
	 * 查询全部员工集合
	 *
	 */
	@Override
	public List<Staff> findAllStaffs(){
		return this.staffDao.findAllStaffs();
	}

	/**
	 * 查询所有员工集合(只提取ID 和 Name)
	 *
	 */
	@Override
	public List<Staff> findAllStaffsWithIdName(){
		//TODO:请在此校验参数的合法性
		this.validateFindAllStaffsWithIdName();
		return this.staffDao.findAllStaffsWithIdName();
	}

	/**
	 * 根据名称查询员工集合(只提取ID 和 Name)
	 *
	 * @param staffName 名称
	 */
	@Override
	public List<Staff> findStaffsWithIdNameByName(String staffName){
		//TODO:请在此校验参数的合法性
		this.validateFindStaffsWithIdNameByName(staffName);
		//TODO:缓存取对应参数
		Set<String> keys = stringRedisTemplate.keys("searchData:Staff_where_staffName_" + staffName);
		List<Staff> staffs = new ArrayList<>();
		if (keys.isEmpty()) {
		staffs = this.staffDao.findStaffsWithIdNameByName(staffName);
		redisTemplate.opsForValue().set("searchData:Staff_where_staffName_" + staffName, staffs, 30, TimeUnit.DAYS);
		} else {
		staffs = redisTemplate.opsForValue().get("searchData:Staff_where_staffName_" + staffName);
		}
		return staffs;
	}

	/**
	 * 根据ID查询指定的员工(只提取ID 和 Name)
	 *
	 * @param staffId Id
	 */
	@Override
	public Staff findStaffsWithIdNameById(Long staffId){
		//TODO:请在此校验参数的合法性
		this.validateFindStaffsWithIdNameById(staffId);
		return this.staffDao.findStaffsWithIdNameById(staffId);
	}

	/**
	 * 根据ID查询指定的员工
	 *
	 * @param staffId Id
	 */
	@Override
	public Staff findStaff(Long staffId){
		//TODO:请在此校验参数的合法性
		this.validateFindStaff(staffId);
		return this.staffDao.findStaff(staffId);
	}

	/**
	 * 根据ID查询指定的员工(包含外键)
	 *
	 * @param staffId Id
	 */
	@Override
	public Staff findStaffWithForeignName(Long staffId){
		//TODO:请在此校验参数的合法性
		this.validateFindStaffWithForeignName(staffId);
		return this.staffDao.findStaffWithForeignName(staffId);
	}

	/**
	 * 新增员工
	 *
	 * @param staff 实体对象
	 */
	@Override
	public Staff saveStaff(Staff staff){
		//TODO:请在此校验参数的合法性
		this.validateSaveStaff(staff);
		//TODO:填充公共参数
		this.setSavePulicColumns(staff);
		Long rows = this.staffDao.saveStaff(staff);
		if(rows != 1)
		{
			String error = "新增保存员工出错，数据库应该返回1,但返回了 "+rows;
			throw new BusinessException(error);
		}
		return staff;
	}

	/**
	 * 更新员工
	 *
	 * @param staff 实体对象
	 */
	@Override
	public Staff updateStaff(Staff staff){
		//TODO:请在此校验参数的合法性
		this.validateUpdateStaff(staff);
		Long rows = this.staffDao.updateStaff(staff);
		if(rows != 1)
		{
			String error = "修改保存员工出错，数据库应该返回1,但返回了 "+rows+",数据可能被删除";
			throw new BusinessException(error);
		}
		return staff;
	}

	/**
	 * 根据ID删除员工
	 *
	 * @param staffId ID
	 */
	@Override
	public void deleteStaff(Long staffId){
		//TODO:请在此校验参数的合法性
		this.validateDeleteStaff(staffId);

		Map<Class<? extends BaseEntity>,EntityUsage> entityUsageMap = this.checkForeignEntity(Staff.class, staffId);
		if(entityUsageMap != null && entityUsageMap.size() >0){
			StringBuilder errors = new StringBuilder();
			errors.append("计划删除的数据正在被以下数引用\n");
			for(EntityUsage entityUsage : entityUsageMap.values()){
				errors.append("\t").append(entityUsage.getEntityLabel()).append("\n");
				for(Map.Entry<Long,String> entry : entityUsage.getUsageIdNames().entrySet() ){
					errors.append("\t\t").append(entry.getKey()).append("\t").append(entry.getValue()).append("\n");
				}
			}
			errors.append("，不能删除，请检查处理后再删除");
			throw  new BusinessException(errors.toString());
		}

		Long rows = this.staffDao.deleteStaff(staffId);
		if(rows != 1){
			String error = "删除员工出错，数据可能已经被删除";
			throw new BusinessException(error);
		}
	}
	@Autowired
	private UserService userService;
	@Override
	public JsonResult generateUser(List<Staff> staffs) {
		staffs.forEach(staff -> {
			User user = new User();
			user.setUsername(staff.getContactTel());
			user.setPassword(userService.encodePsw("123456"));
			user.setState(0L);
			user.setEmail(staff.getEmail());
			user.setPhone(staff.getContactTel());
			user.setNickname(staff.getPost());
			user.setState(0L);
			user.setAvatar("https://cdn.eleadmin.com/20200610/avatar.jpg");
			List<Long> roleIds=this.staffDao.findRoleId(staff.getPost());
			user.setRoleIds(roleIds);
			userService.saveUser(user);
			this.staffDao.updateUserId(staff.getEid(),user.getEid());
		});
		return JsonResult.ok();
	}

	//TODO:---------------验证-------------------

	private void validateFindStaffs(PageDTO pageDTO) {
	//TODO:请使用下面方法添加数据过滤条件
	//		pageDTO.addFilter("creatorId",this.getLoginUserId());
	//TODO:请完善数据校验规则和数据权限判断，如果有问题请抛出异常，参看下面validateUpdateStaff()写法
	}

	private void validateFindStaffsWithIdNameByName(String staffName) {
	//TODO:请完善数据校验规则和数据权限判断，如果有问题请抛出异常，参看下面validateUpdateStaff()写法
	}


	private void validateFindAllStaffsWithIdName() {
	//TODO:请完善数据校验规则和数据权限判断，如果有问题请抛出异常，参看下面validateUpdateStaff()写法
	}

	private void validateFindStaffsWithIdNameById(Long staffId) {
	//TODO:请完善数据校验规则和数据权限判断，如果有问题请抛出异常，参看下面validateUpdateStaff()写法
	}

	private void validateFindStaff(Long staffId) {
	//TODO:请完善数据校验规则和数据权限判断，如果有问题请抛出异常，参看下面validateUpdateStaff()写法
	}

	private void validateFindStaffWithForeignName(Long staffId) {
	//TODO:请完善数据校验规则和数据权限判断，如果有问题请抛出异常，参看下面validateUpdateStaff()写法
	}

	private void validateSaveStaff(Staff staff) {
	//不为空判断
	if (staff.getEid() != null || staff.getCreatorId() != null || staff.getCreateDatetime() != null) {
	throw new BusinessException("非法请求");
	}
	//TODO:请完善数据校验规则和数据权限判断，如果有问题请抛出异常，参看下面validateUpdateStaff()写法
	}

	private void validateUpdateStaff(Staff staff) {
	//不为空判断
	if (staff.getEid() == null) {
	throw new BusinessException("唯一标识不能为空");
	}
	//是否存在判断
	if (this.staffDao.findStaffTotalCount(PageDTO.create(Staff.FIELD_ID, staff.getEid())) == 0) {
	throw new BusinessException("修改的员工 " + staff.getName() + " 不存在，修改失败，请重试或联系管理员");
	}
	//TODO:请完善数据校验规则和数据权限判断，如果有问题请抛出异常，参看下面validateUpdateStaff()写法
	}

	private void validateDeleteStaff(Long staffId) {
	//TODO:请完善数据校验规则和数据权限判断，如果有问题请抛出异常，参看下面validateUpdateStaff()写法
	}

	@Override
	public boolean canDownloadAttachment(String formName, Long id) {
	return true;
	}
}
